package com.lock.readwrite;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @PackageName:com.lock.readwrite
 * @ClassName:test01
 * @Description: readWriteLockd读写锁可以实现多个线程同时读取共享数据  读读共享
 * @Author: zhangxiaoyu
 * @date 2021/3/8 15:01
 */
public class test01 {

    static  class Srevice{
        //定义读写锁
        ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
        //定义方法读取数据
        public void read(){
            try {
                readWriteLock.readLock().lock();  //获得读锁
                System.out.println(Thread.currentThread().getName()+"获取读锁，开始读取数据的时间---"+System.currentTimeMillis());
                TimeUnit.SECONDS.sleep(3); //
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                readWriteLock.readLock().unlock(); //释放锁
            }
        }
    }

    public static void main(String[] args){
        Srevice service = new Srevice();
        //创建5个线程，调用read
        for (int i=0;i<5;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    service.read();   //读取数据
                }
            }).start();
        }
        //运行程序后，这多个线程几乎可以同时获得读锁，执行lock后面的代码
    }

}


